package flinkSql.window.group;

import bean.SensorReading;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Session;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import org.junit.Test;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.lit;

//TODO 事件时间会话窗口
public class Flink_EventTime_GroupWindow_Session {

    @Test
    public void test() throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);

        SingleOutputStreamOperator<SensorReading> input = env.socketTextStream("node193", 9999)
                .map(new MapFunction<String, SensorReading>() {
                    @Override
                    public SensorReading map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new SensorReading(split[0], Long.parseLong(split[1]), Double.parseDouble(split[2]));
                    }
                });

        WatermarkStrategy<SensorReading> watermarkStrategy = WatermarkStrategy.<SensorReading>forBoundedOutOfOrderness(Duration.ofSeconds(1))
                .withTimestampAssigner((SerializableTimestampAssigner<SensorReading>) (element, recordTimestamp) -> element.getTs());

        SingleOutputStreamOperator<SensorReading> input2 = input.assignTimestampsAndWatermarks(watermarkStrategy);

        Table table = tableEnvironment.fromDataStream(input2, $("id"), $("ts"), $("temp"), $("rt").rowtime());

        //table API风格
        Table select = table.window(Session.withGap(lit(5).seconds()).on($("rt")).as("rt"))
                .groupBy($("id"), $("rt"))
                .select($("id"), $("temp").sum());

        //sql 风格
        tableEnvironment.createTemporaryView("sqlTable",table);
        Table select2 = tableEnvironment.sqlQuery("select id,sum(temp) from sqlTable group by id,session(rt,interval '10' second)");

        tableEnvironment.toAppendStream(select,Row.class).print("table");
        tableEnvironment.toAppendStream(select2,Row.class).print("sql");

        env.execute();

    }
}
